<template>
  <div class="gm-xc">
    <div class="label">
      <el-tag
        :class="activeFlog === 1 ? 'active' : ''"
        :effect="activeFlog === 1 ? 'dark' : 'light'"
        @click="createAlbum()"
      >创建相册</el-tag>
      <el-tag
        :class="activeFlog === 2 ? 'active' : ''"
        type="success"
        :effect="activeFlog === 2 ? 'dark' : 'light'"
        @click="uploadPhoto()"
      >上传照片</el-tag>
    </div>
    <div class="photo-album" v-show="activeFlog === 1">
      <div class="title">创建相册</div>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="相册名称" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="相册描述" prop="desc">
          <el-input type="textarea" v-model="ruleForm.desc" :autosize="{ minRows: 3, maxRows: 8}"></el-input>
        </el-form-item>
        <el-form-item label="相册权限" prop="state">
          <el-radio-group v-model="ruleForm.state">
            <el-radio :label="!!1">公开</el-radio>
            <el-radio :label="!!0">私密</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="相册标签">
          <el-checkbox-group v-model="ruleForm.tags">
            <el-checkbox label="家庭" name="type"></el-checkbox>
            <el-checkbox label="工作" name="type"></el-checkbox>
            <el-checkbox label="风景" name="type"></el-checkbox>
            <el-checkbox label="电影" name="type"></el-checkbox>
            <el-checkbox label="动漫" name="type"></el-checkbox>
            <el-checkbox label="技术" name="type"></el-checkbox>
            <el-checkbox label="生活" name="type"></el-checkbox>
            <el-checkbox label="其他" name="type"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitFormRuleForm('ruleForm')">立即创建</el-button>
          <el-button @click="resetRuleForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="upload-photo" v-show="activeFlog === 2">
      <div class="title">上传照片到相册</div>
      <el-form
        :model="uploadForm"
        :rules="rules2"
        ref="uploadForm"
        label-width="100px"
        class="demo-uploadForm"
      >
        <el-form-item class="change-album" label="选择相册" prop="album">
          <el-select v-model="uploadForm.album" placeholder="请选择相册">
            <el-option
              v-for="data in albumsData"
              :key="data.name"
              :label="data.name"
              :value="data.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-upload
          class="upload"
          action
          list-type="picture-card"
          :limit="limitNum"
          :http-request="addAttachment"
          :before-upload="beforeAvatarUpload"
        >
          <i class="el-icon-plus"></i>
        </el-upload>

        <el-dialog
          title="图片介绍"
          :visible.sync="dialogVisible"
          width="30%"
          :before-close="handleClose"
        >
          <el-input
            v-model="alertData.label"
            placeholder="图片标题"
            style="margin-bottom: 30px"
            maxlength="24"
            show-word-limit
          ></el-input>
          <el-input
            type="textarea"
            v-model="alertData.body"
            placeholder="图片描述"
            maxlength="80"
            show-word-limit
          ></el-input>
          <el-checkbox-group v-model="alertData.hot" style="margin-top: 20px">
            <el-checkbox label="热门" name="type"></el-checkbox>
          </el-checkbox-group>
          <span slot="footer" class="dialog-footer">
            <el-button @click="handleClear()">取 消</el-button>
            <el-button type="primary" @click="addInfo()">确 定</el-button>
          </span>
        </el-dialog>

        <div class="async-load">
          <ul v-if="uploadForm.photos.length">
            <li v-for="(data, index) in uploadForm.photos" :key="data.id">
              <div class="photo-desc">{{ `第${index + 1}张图片描述：` }}</div>
              <div class="hot">
                <p>
                  图片标题：
                  <span>{{ data.label }}</span>
                </p>
                <p>
                  热门标签：
                  <span>{{ data.hot ? "是" : "否" }}</span>
                </p>
              </div>
              <p>
                图片描述：
                <span>{{ data.body }}</span>
              </p>
            </li>
          </ul>
        </div>

        <el-form-item class="btn">
          <el-button
            type="primary"
            :disabled="btnDisabled"
            @click="submitFormUploadForm('uploadForm')"
          >立即上传</el-button>
          <el-button @click="resetUploadForm('uploadForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from "Vuex";
import { userUrl } from "@/public/uri.js";
// import qs from "qs";
export default {
  data() {
    return {
      ruleForm: {
        name: "",
        desc: "",
        state: true,
        tags: []
      },
      btnDisabled: false,
      activeFlog: 1,
      uploadForm: {
        album: "",
        photos: [],
        fileData: []
      },
      alertData: {
        label: "",
        body: "",
        hot: false
      },
      dialogVisible: false,
      limitNum: 5,

      rules: {
        name: [
          { required: true, message: "请输入相册名称", trigger: "blur" },
          { min: 2, max: 24, message: "长度在 2 到 24 个字符", trigger: "blur" }
        ],
        state: [
          { required: true, message: "请选择相册状态", trigger: "change" }
        ],
        desc: [
          { required: true, message: "请填写相册描述", trigger: "blur" },
          {
            min: 2,
            max: 120,
            message: "长度在 2 到 120 个字符",
            trigger: "blur"
          }
        ]
      },
      rules2: {
        album: [{ required: true, message: "请选择相册", trigger: "change" }]
      }
    };
  },
  watch: {
    "uploadForm.fileData"() {
      this.alertData.label = "";
      this.alertData.body = "";
      this.alertData.hot = false;
      this.dialogVisible = true;
    }
  },
  computed: {
    ...mapState("user", ["albumsData", "userName"])
  },
  methods: {
    submitFormUploadForm(formName) {
      // 上传照片数据到相册
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.uploadForm.photos.length) {
            this.btnDisabled = true;
            this.$notify.info({
              title: "消息",
              message: "请稍后，正在上传照片。"
            });
            let collections = new FormData();
            const fileData = this.uploadForm.fileData;
            for (let i = 0; i < fileData.length; i++) {
              collections.append(
                "photos",
                JSON.stringify(this.uploadForm.photos[i])
              );
              collections.append("image", this.uploadForm.fileData[i]);
            }
            collections.append("album", this.uploadForm.album);
            collections.append("userName", this.userName);

            if (this.uploadForm.photos.length > 1) {
              collections.append("dataType", 1);
            }
            // collections.append(
            //   "photos",
            //   JSON.stringify(this.uploadForm.photos)
            // );

            this.$axios
              .post(`${userUrl}/userdata/setphotos`, collections)
              .then(res => {
                if (res.data.ok === 1) {
                  this.btnDisabled = false;
                  this.$notify({
                    title: "消息",
                    type: "success",
                    message: "上传照片成功。"
                  });
                  this.getUserInfoData(this.userName);
                  this.getUserPhotosData(this.userName);
                  this.getAlbumsData(this.userName);
                  this.$alert(res.data.data);
                } else {
                  console.log(res.data);
                }
              })
              .catch(err => {
                console.log("错误信息：" + err);
              });
          } else {
            this.$alert("请至少选择一张相片！");
          }
        }
      });
    },
    uploadPhoto() {
      // 上传照片的tag按钮触发事件
      this.activeFlog = 2;
      this.getAlbumsMethods();
    },
    getAlbumsMethods() {
      // 获取相册的数据集合
      this.getAlbumsData(this.userName);
    },
    createAlbum() {
      // 创建相册的tag按钮触发事件
      this.activeFlog = 1;
    },
    handleClear() {
      this.$confirm("是否清除填写内容并退出？，（建议填写图片介绍）", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.alertData.label = "";
          this.alertData.body = "";
          this.alertData.hot = false;
          this.addInfo();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消退出，你可以继续操作！"
          });
        });
    },
    handleClose() {
      if (this.alertData.label && this.alertData.body) {
        this.addInfo();
      } else {
        this.$confirm("还有图片介绍未填写项，是否退出界面", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.addInfo();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消退出，你可以继续操作！"
            });
          });
      }
    },
    addInfo() {
      this.uploadForm.photos.push(JSON.parse(JSON.stringify(this.alertData)));
      this.dialogVisible = false;
    },
    submitFormRuleForm(formName) {
      // 提交创建的相册到数据库
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (!this.ruleForm.userName) {
            this.ruleForm.userName = this.userName;
          }
          this.$axios
            .get(`${userUrl}/userdata/setalbums`, {
              params: this.ruleForm,
              paramsSerializer: params => {
                return qs.stringify(params, { indices: false });
              }
            })
            .then(res => {
              if (res.data.ok === 1) {
                this.getUserInfoData(this.userName);
                this.getAlbumsData(this.userName);
                this.$confirm(
                  "相册创建成功，是否现在上传相片到相册？",
                  "提示",
                  {
                    confirmButtonText: "上传",
                    cancelButtonText: "取消",
                    type: "info"
                  }
                )
                  .then(() => {
                    this.uploadPhoto();
                  })
                  .catch(() => {
                    this.resetRuleForm("ruleForm");
                  });
              } else {
                this.$alert(`${res.data.data}`, "提示", {
                  confirmButtonText: "确定",
                  callback: action => {
                    this.ruleForm.name = "";
                  }
                });
              }
            })
            .catch(err => {
              console.log("错误信息：" + err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    addAttachment(file) {
      this.uploadForm.fileData.push(file.file);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/png" || file.type === "image/jpeg";
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt1M) {
        this.$message.error("上传头像图片大小不能超过 1MB!");
      }
      return isJPG && isLt1M;
    },
    resetRuleForm(formName) {
      // 清除创建相册的数据集合ruleForm
      this.$refs[formName].resetFields();
    },
    resetUploadForm(formName) {
      // 清除上传照片的数据集合uploadForm
      this.$refs[formName].resetFields();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    ...mapActions("user", [
      "getAlbumsData",
      "getUserInfoData",
      "getUserPhotosData"
    ])
  }
};
</script>

<style lang="sass" scoped>
@import '@/assets/default.sass'
.gm-xc
  width: 100%
  height: 100%
  padding: 0 5%
  .label
    padding-top: 30px
    width: 100%
    height: 90px
    line-height: 60px
    @include flex(space-between,center)
    .el-tag
      margin-right: 30px
      cursor: pointer
      transition: all .3s
    .active
      width: 100px
      height: 40px
      text-align: center
      line-height: 40px
      transition: all .3s
  .photo-album
    width: 100%
    .title
      width: 100%
      height: 50px
      line-height: 60px
      border-bottom: 1px solid #eee
      color: #333
      font-size: 18px
      font-weight: 700
    .el-form
      margin-top: 50px
      .el-form-item
        margin-top: 50px
  .upload-photo
    .title
      width: 100%
      height: 50px
      line-height: 60px
      border-bottom: 1px solid #eee
      color: #333
      font-size: 18px
      font-weight: 700
    .el-form
      width: 100%
      margin-top: 30px
      .change-album
        line-height: 70px
        height: 70px
      .upload
        margin: 10px 0
        border: 1px solid #eee
      .async-load
        width: 100%
        margin-top: 20px
        >ul
          widht: 100%
          >li
            width: 100%
            height: 105px
            padding: 10px 0
            border-bottom: 1px solid #eee
            .photo-desc
              width: 100%
              height: 30px
              line-height: 30px
              color: #333
              font-size: 16px
            >p
              width: 100%
              height: 30px
              line-height: 30px
              overflow: hidden
              white-space: nowrap
              text-overflow: ellipsis
              >span
                color: #0487dc
            .hot
              width: 100%
              height: 25px
              @include flex(space-between,center) 
              >p                
                >span
                  color: #0487dc
                &:first-child
                  flex: 0 0 80%
                  overflow: hidden
                  white-space: nowrap
                  text-overflow: ellipsis
      .btn
        margin: 50px 0 40px 0
</style>
